package com.alatus.service.impl;

import com.alatus.constant.Constants;
import com.alatus.manager.RedisManager;
import com.alatus.manager.UserManager;
import com.alatus.mapper.TUserMapper;
import com.alatus.model.TUser;
import com.alatus.query.BaseQuery;
import com.alatus.query.UserQuery;
import com.alatus.service.UserService;
import com.alatus.util.CacheUtils;
import com.alatus.util.JWTUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserServiceImpl implements UserService {
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private RedisManager redisManager;
    @Resource
    private UserManager userManager;

//    注入一个密码加密器
    @Resource
    private PasswordEncoder passwordEncoder;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TUser tUser = tUserMapper.selectByLoginAct(username);
        if(tUser == null){
            throw new UsernameNotFoundException("登陆账号不存在");
        }
//        获取用户ID
        Integer id = tUser.getId();
//        设置用户的角色
        tUser.setRoleList(userManager.loadRoleListByUser(id));
        tUser.setMenuPermissionList(userManager.getMenuPermissionList(id));
        List<String> permissionList = new ArrayList<>();
        userManager.selectButtonPermissionByUserId(id).forEach(tPermission ->  {
//            这里的code就是权限标识符
            permissionList.add(tPermission.getCode());
        });
//        设置用户的权限标识符
        tUser.setPermissionList(permissionList);
        return tUser;
    }

    @Override
    public PageInfo<TUser> getUserByPage(Integer current) {
//        设置PageHelper和分页情况
        PageHelper.startPage(current, Constants.PAGE_SIZE);
//        查询
        ArrayList<TUser> list = tUserMapper.selectUserByPage(BaseQuery.builder().build());
//        封装分页到PageInfo中
        PageInfo<TUser> info = new PageInfo<>(list);
        return info;
    }

    @Override
    public TUser getUserById(Integer id) {
        return tUserMapper.selectDetailByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveUser(UserQuery userQuery) {
        TUser tUser = new TUser();
//        把query对象的数据复制到user对象里面
//        这个工具类的复制要求是两个对象的属性名要相同,属性要相同
        BeanUtils.copyProperties(userQuery,tUser);
        tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
//        创建时间
        tUser.setCreateTime(new Date());
//        通过token解析出的用户获取ID作为创建者的ID
        Integer loginId = JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setCreateBy(loginId);
        return tUserMapper.insertSelective(tUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateUser(UserQuery userQuery) {
        TUser tUser = new TUser();
//        把query对象的数据复制到user对象里面
//        这个工具类的复制要求是两个对象的属性名要相同,属性要相同
        BeanUtils.copyProperties(userQuery,tUser);
        if(StringUtils.hasText(userQuery.getLoginPwd())){
            tUser.setLoginPwd(passwordEncoder.encode(userQuery.getLoginPwd()));
        }
//        编辑时间
        tUser.setEditTime(new Date());
//        通过token解析出的用户获取ID作为编辑者的ID
        Integer loginId = JWTUtils.parseUserFromJWT(userQuery.getToken()).getId();
        tUser.setEditBy(loginId);
        return tUserMapper.updateByPrimaryKeySelective(tUser);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delUserById(Integer id) {
        return tUserMapper.deleteByPrimaryKey(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delUsersByIds(List<String> idList) {
//        遍历删除法
//        int result = 0;
//        for (int i = 0; i < idList.size(); i++) {
//            result += tUserMapper.deleteByPrimaryKey(Integer.parseInt(idList.get(i)));
//        }
//        return result;
        return tUserMapper.deleteByIds(idList);
    }

    @Override
    public List<TUser> getOwnerList() {
//        先从redis获取
//        redis没有就走mysql
        return CacheUtils.getCacheData(() -> {
//            从redis查数据
            return (List<TUser>)redisManager.getValue(Constants.OWNER_KEY);
        }
        ,() -> {
//            生产,从mysql查询数据
            return (List<TUser>)tUserMapper.selectByOwner();
        }
        ,(t) -> {
//            消费,把数据放入缓存redis
            redisManager.setValue(Constants.OWNER_KEY,t);
        });
    }
}
